package com.swdc.dc;

import java.util.ArrayList;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class ContactPicker extends Activity{

	public static final String NAME_CODE = "name";
	private ArrayList<String> contacts_list;
	
	public void onCreate(Bundle savedInstanceState){
		
		super.onCreate(savedInstanceState);
		setContentView(R.layout.contact_picker);
		
		contacts_list = new ArrayList<String>();
		initList();
		
		ListView contacts = (ListView) findViewById(R.id.cp_contact_list);
		
		contacts.setAdapter(new ArrayAdapter<String>(this, R.layout.list_item, contacts_list));
		
		contacts.setOnItemClickListener(new OnItemClickListener() {

			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
				
				Intent result = new Intent();
				result.putExtra(NAME_CODE, contacts_list.get(arg2));
				setResult(RESULT_OK, result);
				finish();
			}
		});
	}
	
	private void initList(){
		
		ContentResolver cr = getContentResolver();
	    Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,null, null, null, null);
	    
	    if (cur.getCount() > 0) {
	    
		    while (cur.moveToNext()) {
		    	
		        contacts_list.add(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)));
		    }
	    }
	}
}
